package com.course.server.service.discusspost;

import com.alibaba.fastjson.JSONObject;
import com.course.server.domain.Member;
import com.course.server.domain.discusspost.Message;
import com.course.server.dto.PageDto;
import com.course.server.mapper.my.MessageMapper;
import com.course.server.service.MemberService;
import com.course.server.util.HostHolder;
import com.course.server.util.SensitiveFilter;
import com.course.server.util.UuidUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Autowired
    private MessageService messageService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MemberService memberService;

    public void findConversations(PageDto pageDto) {

        Member member = hostHolder.getMember();
        String userId;
        if(member !=null){
            userId= member.getId();
        }else{
            throw new RuntimeException("用户未登录!");
        }
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        List<Message> messageList = messageMapper.selectConversations(userId);
        PageInfo<Message> pageInfo = new PageInfo<>(messageList);
        pageDto.setTotal(pageInfo.getTotal());
        List<Map<String, Object>> conversations = new ArrayList<>();
        for (Message message : messageList) {
            Map<String,Object> map=new HashMap();
            map.put("conversation", message);
            map.put("letterCount", messageService.findLetterCount(message.getConversationId()));
            map.put("unreadCount", messageService.findLetterUnreadCount(userId, message.getConversationId()));
            String targetId = userId.equals(message.getFromId()) ? message.getToId() : message.getFromId();
            map.put("target", memberService.findUserById(targetId));
            conversations.add(map);
        }
        Map<String,Object> dto=new HashMap();
        dto.put("conversations", conversations);

        // 查询未读消息数量
        int letterUnreadCount = messageService.findLetterUnreadCount(userId, null);
        dto.put("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.findNoticeUnreadCount(userId, null);
        dto.put("noticeUnreadCount", noticeUnreadCount);

        pageDto.setMap(dto);
    }

    public int findConversationCount(String userId) {
        return messageMapper.selectConversationCount(userId);
    }

    public void findLetters(String conversationId,PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        // 私信列表
        List<Message> letterList = messageMapper.selectLetters(conversationId);
        PageInfo<Message> pageInfo = new PageInfo<>(letterList);
        pageDto.setTotal(pageInfo.getTotal());
        List<Map<String, Object>> letters = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                Map<String, Object> map = new HashMap<>();
                map.put("letter", message);
                map.put("fromUser", memberService.findUserById(message.getFromId()));
                letters.add(map);
            }
        }
        Map<String,Object> dto=new HashMap<>();
        dto.put("letters", letters);

        // 私信目标
        dto.put("target", getLetterTarget(conversationId));

        // 设置已读
        List<String> ids = getLetterIds(letterList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
        pageDto.setMap(dto);

    }

    private Member getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        String id0 = ids[0];
        String id1 = ids[1];

        if (hostHolder.getMember().getId().equals(id0) ) {
            return memberService.findUserById(id1);
        } else {
            return memberService.findUserById(id0);
        }
    }

    private List<String> getLetterIds(List<Message> letterList) {
        List<String> ids = new ArrayList<>();

        if (letterList != null) {
            for (Message message : letterList) {
                if (hostHolder.getMember().getId().equals(message.getToId())  && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }

    public int findLetterCount(String conversationId) {
        return messageMapper.selectLetterCount(conversationId);
    }

    public int findLetterUnreadCount(String memberId, String conversationId) {
        return messageMapper.selectLetterUnreadCount(memberId, conversationId);
    }

    public int addMessage(Message message) {
//        message.setContent(HtmlUtils.htmlEscape(message.getContent()));
        message.setContent(message.getContent());
        message.setContent(sensitiveFilter.filter(message.getContent()));
        message.setId(UuidUtil.getShortUuid());
        return messageMapper.insertMessage(message);
    }

    public int readMessage(List<String> ids) {
        return messageMapper.updateStatus(ids, 1);
    }

    public int deleteMessage(String id) {
        return messageMapper.updateStatus(Arrays.asList(new String[]{id}), 2);
    }

    public Message findLatestNotice(String userId, String topic) {
        return messageMapper.selectLatestNotice(userId, topic);
    }

    public int findNoticeCount(String userId, String topic) {
        return messageMapper.selectNoticeCount(userId, topic);
    }

    public int findNoticeUnreadCount(String userId, String topic) {
        return messageMapper.selectNoticeUnreadCount(userId, topic);
    }

    public void findNotices(String topic,PageDto pageDto) {
        Member member = hostHolder.getMember();

        PageHelper.startPage(pageDto.getPage(), pageDto.getSize());
        List<Message> noticeList = messageMapper.selectNotices(member.getId(), topic);
        PageInfo<Message> pageInfo = new PageInfo<>(noticeList);
        pageDto.setTotal(pageInfo.getTotal());

        List<Map<String, Object>> noticeVoList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                Map<String, Object> map = new HashMap<>();
                // 通知
                map.put("notice", notice);
                // 内容
//                String content = HtmlUtils.htmlUnescape(notice.getContent());//todo 不应该使用HtmlUtils.htmlUnescape(和HtmlUtils.htmlescape(，数据库已经有的这种脏数据需要删除掉。https://www.w3school.com.cn/jsref/jsref_unescape.asp
                String content = notice.getContent();//todo 不应该使用HtmlUtils.htmlUnescape(和HtmlUtils.htmlescape(，数据库已经有的这种脏数据需要删除掉。https://www.w3school.com.cn/jsref/jsref_unescape.asp
                Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user", memberService.findUserById((String) data.get("userId")));
                map.put("entityType", data.get("entityType"));
                map.put("entityId", data.get("entityId"));
                map.put("postId", data.get("postId"));
                map.put("fromUser", memberService.findUserById(notice.getFromId()));//系统用户，用户id是1。

                noticeVoList.add(map);
            }
        }

        pageDto.setList(noticeVoList);
        // 设置已读
        List<String> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }
    }

}
